package com.young.weixin.service.impl;

import com.qq.weixin.mp.aes.WXBizMsgCrypt;
import com.young.common.util.CollectionUtil;
import com.young.common.util.JsonUtil;
import com.young.weixin.configure.WxConfigure;
import com.young.weixin.core.IWxMessageProcess;
import com.young.weixin.model.WxMessageRequest;
import com.young.weixin.model.enums.EWxEventTypeEnum;
import com.young.weixin.model.enums.EWxMessageTypeEnum;
import com.young.weixin.model.message.WxBaseMessage;
import com.young.weixin.model.message.WxEventMessage;
import com.young.weixin.model.message.WxMessageMapWrapper;
import com.young.weixin.service.IWxMessageService;
import com.young.weixin.util.WxMessageBuilder;
import com.young.weixin.util.WxUtil;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 微信消息服务
 *
 * @author wangjiyu
 * @date 2021/10/5 15:47
 */
@Service
public class WxMessageServiceImpl implements IWxMessageService {

    private static final Logger logger = LoggerFactory.getLogger(WxMessageServiceImpl.class);

    /**
     * 配置
     */
    @Autowired
    private WxConfigure wxConfigure;
    /**
     * 消息处理器集合
     */
    @Autowired
    private List<IWxMessageProcess> messageProcessList;

    /**
     * 处理微信消息
     *
     * @param app              应用
     * @param wxMessageRequest 消息请求参数
     * @param body             消息请求body体
     * @return 回复内容
     */
    @Override
    public String handleWxMessage(String app, WxMessageRequest wxMessageRequest, String body) throws Exception {
        // 解密消息内容
        WxMessageMapWrapper messageMapWrapper = WxUtil.checkAndConvertXmlParam(wxMessageRequest, body, wxConfigure.getToken(), wxConfigure.getEncodingAESKey(), wxConfigure.getAppid());
        logger.info("[处理微信消息] 解密后数据为:{}", messageMapWrapper);

        // 转换消息对象
        WxBaseMessage userMessage = WxMessageBuilder.convertMap2Message(messageMapWrapper);
        if (userMessage == null) {
            return null;
        }

        WxBaseMessage backMsg = null;

        if (CollectionUtil.isNotEmpty(messageProcessList)) {
            // 匹配消息处理器
            IWxMessageProcess matchMessageProcess = null;
            for (IWxMessageProcess messageProcess : messageProcessList) {
                if (!messageProcess.filter(app, userMessage)) {
                    logger.info("[处理微信消息] 该消息处理器不处理当前消息,处理器={},处理器顺序={},app={},消息类型={}"
                            , messageProcess.getClass().getSimpleName(), messageProcess.getOrder(), app, userMessage.getMsgType());
                    continue;
                }
                logger.info("[处理微信消息] 当前消息匹配到消息处理器,处理器={},处理器顺序={},app={},消息类型={}"
                        , messageProcess.getClass().getSimpleName(), messageProcess.getOrder(), app, userMessage.getMsgType());
                matchMessageProcess = messageProcess;
                break;
            }
            if (matchMessageProcess != null) {
                backMsg = matchMessageProcess.process(app, userMessage);
                logger.info("[处理微信消息] 消息处理器返回结果={}", JsonUtil.toJson(backMsg));
            } else {
                logger.info("[处理微信消息] 当前消息没有匹配到任何处理器,app={},消息类型={}", app, userMessage.getMsgType());
            }
        }

        // 返回消息对象
        return backMsg != null ? backMsg.toXml() : WxMessageBuilder.buildBackTextMessage("", userMessage).toXml();
    }


}
